# -- coding: UTF-8 --

# vowei.py - vowei integration for svn
#
# copyright 2010 Shi Yimin <yimin_shi@hotmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License versoin 2 or any later version
import urllib2, urlparse, json, re, httplib
import locale
from ntlm import HTTPNtlmAuthHandler

class vowei_hook_base(object):    
    _defaultbug_re = (r'#(\d+)')
    _defaultguid_re = (r'#{?([A-F0-9]{8,8}\-[A-F0-9]{4,4}\-[A-F0-9]{4,4}\-[A-F0-9]{4,4}\-[A-F0-9]{12,12})}?')
    bug_re = re.compile(_defaultbug_re, re.IGNORECASE)
    guid_re = re.compile(_defaultguid_re, re.IGNORECASE)
    bDebug = True

    def __init__(self):
        self.read_config()

    def debug_print(self, message):
        if ( self.bDebug ):
		f = open('G:\\vowei_hook.log', 'a')
		f.write(message)
		f.write('\n')
		f.close

    def read_config(self):
        pass

    def configitems(self, section):
        pass
            
    def find_work_item_ids(self, message):
        start = 0
        ids = set()
        while True:
            gm = self.guid_re.search(message, start)            
            if gm:
                ids.add(gm.group(1))
                start = gm.end()
                continue
                
            nm = self.bug_re.search(message, start)            
            if nm:
                ids.add(int(nm.group(1)))
                start = nm.end()
            else:
                break
            
        return ids
            
    def map_committer(self, user):
        '''map name of committer to vowei user name.'''
        for committer, bzuser in self.configitems('usermap'):
            if committer.lower() == user.lower():
                return bzuser
        return user

    def create_comments(self, description, commiter, changeid, ids):
        comments = []
        user = self.map_committer(commiter)
        
        for id in ids:
            self.debug_print('format message')
            self.debug_print(str(id))
            message = (u'Change set [%s] is made for work item %s. \n \
                        --------------------------------------------\n \
                        %s') % (changeid, str(id), description)            
            comments.append({
                'PostId': str(id),
                'PostType': 'Ticket',
                'Text': message.decode(locale.getpreferredencoding()),
                'User': user.decode(locale.getpreferredencoding())
            })

        return comments

    def post_data_via_ntlm_channel(self, url, user, password, data):
        http_body = json.dumps(data)      
        headers = {"Content-type": "application/json; charset=utf-8",
                   "Accept": "text/plain"}
        
        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        self.debug_print(user)
        passman.add_password(None, url.decode(locale.getpreferredencoding()), user.decode(locale.getpreferredencoding()), password.decode(locale.getpreferredencoding()))
        
        auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
        opener = urllib2.build_opener(auth_NTLM)
        urllib2.install_opener(opener)

        request = urllib2.Request(url.decode(locale.getpreferredencoding()), http_body, headers)        
        response = urllib2.urlopen(request)
        response.close()
